package com.cnsugar.common.reflect.impl;

import com.cnsugar.common.reflect.BeanField;
import com.cnsugar.common.reflect.IFieldConverter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import static com.cnsugar.common.reflect.ReflectUtils.*;

/**
 * @Description Field生成带setter、getter方法的BeanField
 * @Author Sugar
 * @Date 2020/10/9 11:53
 */
@Slf4j
public class BeanFieldConverter implements IFieldConverter<BeanField> {
    @Override
    public BeanField convert(Class clazz, Field field) {
        Method setter = null;
        String setterName = getSetterMethodName(field);
        try {
            setter = clazz.getMethod(setterName, field.getType());
        } catch (NoSuchMethodException e) {
            //如果没有参数为该属性的数据类型的set方法，则再找名字相同的其他set方法，以兼容重写了set方法的情况
            setter = getSetterMethod(clazz, field);
            if (setter == null) {
                if (log.isDebugEnabled()) {
                    log.debug("!No setter method: {}", field.getName());
                }
            }
        }
        Method getter = null;
        String getterName = getGetterMethodName(field);
        try {
            getter = clazz.getMethod(getterName);
        } catch (NoSuchMethodException e) {
            //如果boolean类型属性无对应的isXxx()方法，则再找对应的getXxx()方法
            if (getterName.startsWith("is")) {
                getterName = "get" + getterName.substring(2);
                try {
                    getter = clazz.getMethod(getterName);
                } catch (NoSuchMethodException ex) {
                    if (log.isDebugEnabled()) {
                        log.debug("!No getter method: {}", field.getName());
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("!No getter method: {}", field.getName());
                }
            }
        }
        return new BeanField(field, setter, getter);
    }
}
